/**
 * 规格列表
 */

'use strict';

var React = require('react-native');
var {msg} = require('iflux-native');
var MktActivity = require('../mkt-activity');
var NumberInput = require('./number-input');
var HEIGHT = require('Dimensions').get('window').height;
var QMBtnContainer = require('../button');

var {
  View,
  ListView,
  Text,
  TextInput,
  TouchableOpacity,
  StyleSheet,
  Image,
  PixelRatio,
  Platform,
} = React;


/**
 * 商品规格列表
 */
var SpecList = React.createClass({
  getDefaultProps() {
    return {
      //单位
      unit: '',
      //sku列表
      skuProps: [],
      //最后一个sku的属性
      skuLastProps: [],
      //数据源
      dataSource: [],
      // 商品名称，如果是无规格商品，规格值默认显示该名称
      productName: ''
    };
  },


  getInitialState() {
    return {
      dataSource: new ListView.DataSource({
        rowHasChanged: (r1, r2) => r1 != r2
      }),
      skuSource: this.props.skus,
      // 购买数量加按钮状态数组
      numberDisable_add: [],
      // 购买数量减按钮状态数组
      numberDisable_subtract: []
    };
  },


  componentDidMount() {
    //初始化sku数量
    this._text = {};
    var numberDisable_add = [];
    var numberDisable_subtract = [];
    this.props.skuLastProps.forEach((v, k) => {
      this._text[v] = this.props.skus[k].buyCount;
      numberDisable_add.push(true);
      numberDisable_subtract.push(false);
    });

    this.setState({
      numberDisable_add: numberDisable_add,
      numberDisable_subtract: numberDisable_subtract
    });
  },


  componentWillReceiveProps(nextProps) {

    // 文本框的值
    this._text = {};
    var numberDisable_add = [];
    var numberDisable_subtract = [];
    nextProps.skuLastProps.forEach((v, k) => {
      this._text[v] = nextProps.skus[k].buyCount;
      numberDisable_add.push(true);
      numberDisable_subtract.push(false);
    });

    // 如果替换了规格，就重置按钮
    var thisPropsSkuId = this.props.skus[0].skuId;
    var nextPropsSkuId = nextProps.skus[0].skuId;

    if(thisPropsSkuId != nextPropsSkuId) {
      this.setState({
        skuSource: nextProps.skus,
        numberDisable_add: numberDisable_add,
        numberDisable_subtract: numberDisable_subtract
      });
    }
  },


  render() {
    return (
      <ListView
        ref={(listView) => {
          this.listView = listView
        }}
        renderRow={this._renderRow}
        keyboardShouldPersistTaps={false}
        showsVerticalScrollIndicator={true}
        automaticallyAdjustContentInsets={false}
        dataSource={this.state.dataSource.cloneWithRows(this.props.dataSource)}
      />
    );
  },


  /**
   * 渲染每一行
   */
  _renderRow(row, _, index) {
    var isLast = (this.props.dataSource.length - 1) == index;

    if (isLast) {
      var lastList = this.props.skuLastProps;
      //过滤出来迭代的数据
      var slist = row.slist.filter(v => lastList.indexOf(v.svid) != -1);

      //没有可选项直接返回null
      if (lastList.length == 0) {
        return null;
      }

      return (
        <View
          key={index}
          style={styles.lastRowContainer}
          onLayout={this._handleTextLayout.bind(this, index)}>
          {
            row.spnam.length > 0 ? <Text style={[styles.spnam,styles.txt]}>{row.spnam}</Text> : null
          }
          {slist.map((v, k) => {
            return (
              <View key={k} style={styles.lastRow}>
                <View style={styles.lastSpecVal}>
                  <View style={styles.lastSpecValRow}>
                    <View style={styles.lastSpecValPrev}>
                      <Text style={styles.lastSpecValName} numberOfLines={1}>{v.svnam == '' ? this.props.productName : v.svnam}</Text>
                    </View>
                    <Text style={styles.priceText}>￥{(this.state.skuSource[k].price).toFixed(2)}</Text>
                  </View>
                  {/*如果有营销活动显示在可选规格值上面*/}
                  {/*<MktActivity
                    labelGroup={styles.mktActivity}
                    data={this.state.skuSource[k].mkt}/>*/}
                </View>

                <QMBtnContainer
                  style={[styles.inputOper,styles.minus]}
                  onPress={this._handleTextClick.bind(this,'subtract', v.svid, k)}>
                  <Image style={styles.inputIcon} source={this.state.numberDisable_subtract[k] ? require('img/minus_blue.png') : require('img/minus_grey.png')} />
                </QMBtnContainer>

                <View style={styles.inputBox}>
                  <NumberInput
                    value={this.state.skuSource[k].buyCount + ''}
                    onChangeText={this._handleTextChange.bind(this, v.svid, k)}
                    onBlur={this._handleTextBlur.bind(this, v.svid, k, index)}
                    keyboardType='numeric'
                    onFocus={this._handleOnFocus.bind(this, index)}
                    style={styles.textInput}/>
                </View>

                <QMBtnContainer
                  style={[styles.inputOper,styles.plus]}
                  onPress={this._handleTextClick.bind(this,'add', v.svid, k)}>
                  <Image style={styles.inputIcon} source={this.state.numberDisable_add[k] ? require('img/plus_blue.png') : require('img/plus_grey.png')} />
                </QMBtnContainer>
                {/*<Text style={styles.unit}>{this.props.unit}</Text>*/}
              </View>
            );
          })}
        </View>
      );
    }

    return (
      <View key={index} style={styles.listRow}>
        <Text style={styles.spnam}>{row.spnam}</Text>
        <View style={styles.specValContainer}>
        {row.slist.map((v, k) => {
          var isChoose = this.props.skuProps.indexOf(v.svid) != -1;
          return (
            <TouchableOpacity
              key={k}
              onPress={this._handleChooseSpec.bind(this, index, v.svid, v.disable)}
              style={[styles.touchableBorder, {borderColor: isChoose ? '#3d85cc' : '#b5bcc2'}, v.disable == 0 ? styles.disableSpec : '']}>
              <View style={styles.specValWrapper}>
                <Text numberOfLines={1} style={[styles.tab,{color: isChoose ? v.disable == 0 ? '#ebebeb' : '#326da7' : v.disable == 0 ? '#ebebeb' : '#939495'} ]}>{v.svnam}</Text>
                {(isChoose && v.disable != 0) ?
                  <Image style={styles.imgSelected} source={require('img/selected.png')} /> : null
                }
              </View>
            </TouchableOpacity>
          );
        })}
        </View>
      </View>
    );
  },


  _handleTextLayout(index, e) {
    this._textLayout = (this._textLayout || {});
    this._textLayout[index] = e.nativeEvent.layout.y + HEIGHT/2;
  },


  _handleOnFocus(index){
    if (__DEV__) {
      console.log('onFocus:', index);
    }
    //var offset = this._textLayout[index];
    //// 屏幕高度之内
    //if (offset <= HEIGHT && offset > (HEIGHT / 2)) {
    //  this.listView.scrollResponderScrollTo(0, offset - HEIGHT / 2);
    //}
    //// 高出一倍屏幕时
    //else if (offset > HEIGHT){
    //  this.listView.scrollResponderScrollTo(0, offset - HEIGHT + HEIGHT/2);
    //}
  },



  _handleTextChange(svid, index, text) {
    if (__DEV__) {
      console.log('onChangeText', svid, index, text);
    }

    var skus = this.state.skuSource.slice();
    var sku = skus[index];

    if (text == '') {
      sku.buyCount = '';
    } else {
      if (!(/^\d+$/).test(text)) {
        text = 0;
      }
      sku.buyCount = parseInt(text);
    }
    skus[index] = sku;
    this.setState({skuSource: skus});

    if(text != '') {
      this._text[svid] = parseInt(text);
    }else{
      this._text[svid] = 'null';
    }
  },


  /**
   * 购买数量有输入，但大于库存，或小雨最小起订量时，扭正为最小起订量
   * @param svid
   * @param index
   * @private
   */
  _handleTextBlur(svid, index, rowIndex) {
    if (__DEV__) {
      console.log('onBlur', svid, index, rowIndex);
    }

    this.listView.scrollResponderScrollTo(0, 0);
    var text = this._text[svid];

    var numberDisable_add = this.state.numberDisable_add.slice();
    var numberDisable_subtract = this.state.numberDisable_subtract.slice();
    numberDisable_subtract[index] = true;
    numberDisable_add[index] = true;

    var skus = this.state.skuSource.slice();
    var sku = skus[index];

    if(text == 0){
      this._text[svid] = 0;
      sku.buyCount = 0;
      skus[index] = sku;
      numberDisable_subtract[index] = false;
    }

    // 最小起订量
    var minOrderQuantity = sku.minOrderQuantity;
    if ((text < minOrderQuantity || text == 'null') && text != 0) {
      msg.emit('app:tip', '最小起订量为：' + minOrderQuantity);

      this._text[svid] = minOrderQuantity;
      sku.buyCount = minOrderQuantity;
      skus[index] = sku;

      numberDisable_subtract[index] = true;
    }

    // 库存
    var stock = sku.stock;
    if (text > stock) {
      msg.emit('app:tip', '商品库存为：' + stock);

      this._text[svid] = stock;
      sku.buyCount = stock;
      skus[index] = sku;

      numberDisable_add[index] = false;
    }
    this.setState({
      skuSource: skus,
      numberDisable_add: numberDisable_add,
      numberDisable_subtract: numberDisable_subtract
    });
  },


  _handleChooseSpec(index, vid, disable) {
    if(disable != 0) {
      this.props.onSelectSpec(index, vid);
    }
  },


  getShoppingCart() {
    return this._text;
  },

  /**
   * 加减购买数量
   * @param type
   * @param svid
   * @param index
   * @private
   */
  _handleTextClick(type, svid, index){
    if (__DEV__) {
      console.log('_handleTextClick', svid, index);
    }

    var numberDisable_add = this.state.numberDisable_add.slice();
    var numberDisable_subtract = this.state.numberDisable_subtract.slice();

    var skus = this.state.skuSource.slice();
    var sku = skus[index];
    var buyCount = sku.buyCount;

    if(type == 'add') {
      if(!numberDisable_add[index]){
        return;
      }
      buyCount ++ ;
    }else{
      if(!numberDisable_subtract[index]){
        return;
      }
      buyCount -- ;
    }

    if (buyCount >= sku.minOrderQuantity ) {
      numberDisable_subtract[index] = true;
    }else{
      if(type == 'add'){
        buyCount = sku.minOrderQuantity;
        numberDisable_subtract[index] = true;
      }else {
        buyCount = 0;
        numberDisable_subtract[index] = false;
      }
      if(sku.minOrderQuantity != 1) {
        msg.emit('app:tip', '最小起订量为：' + sku.minOrderQuantity);
      }
    }
    this.setState({numberDisable_subtract: numberDisable_subtract})

    if (buyCount < sku.stock) {
      numberDisable_add[index] = true;
    }else{
      numberDisable_add[index] = false;
    }
    this.setState({numberDisable_add: numberDisable_add})

    sku.buyCount = buyCount;
    skus[index] = sku;

    this.setState({skuSource: skus});

    this._text[svid] = parseInt(buyCount);
  }
});


var styles = StyleSheet.create({
  listRow: {
    flex: 1,
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 2,
    paddingLeft: 10,
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1'
  },
  lastRowContainer: {
    paddingTop: 10,
    paddingLeft: 10,
    paddingRight: 10,
    borderBottomColor: '#e1e1e1',
    borderBottomWidth: 1 / PixelRatio.get(),
  },
  lastRow: {
    flex:1,
    paddingBottom: 15,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center'
  },
  lastSpecVal: {
    flex: 1,
    height: 24,
    justifyContent: 'center',
    paddingRight: 15
  },
  lastSpecValName: {
    fontSize: 14,
    color: '#939495'
  },
  specValContainer: {
    flex: 1,
    flexWrap: 'wrap',
    flexDirection: 'row'
  },
  tab: {
    textAlign: 'center',
    paddingLeft: 10,
    paddingRight: 10,
    fontSize: 12,
  },
  mktActivity: {
    paddingTop: 0,
    marginTop: 2
  },
  unit: {
    fontSize: 14,
    color: '#939495',
    marginLeft: 5
  },
  spnam: {
    fontSize: 14,
    paddingBottom: 10,
    color: '#333'
  },
  touchableBorder: {
    marginRight: 8,
    height: 26 + 2 / PixelRatio.get(),
    borderWidth: 2 / PixelRatio.get(),
    justifyContent: 'center',
    marginBottom: 8
  },
  specValWrapper: {
    justifyContent: 'center',
    height: 26,
  },
  imgSelected: {
    position: 'absolute',
    right: 0,
    bottom: 0,
    width: 12,
    height: 12,
    backgroundColor: 'transparent'
  },
  inputBox: {
    borderWidth: 1 / PixelRatio.get(),
    borderColor: '#e1e1e1',
  },
  textInput: {
    color: '#326da7',
    fontSize: 14,
    padding: 0,
    height: 24,
    width: 45,
    backgroundColor: '#fff'
  },
  txt: {
    paddingBottom: 5
  },
  disableSpec: {
    borderColor: '#ebebeb',
  },
  lastSpecValRow: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
  },
  lastSpecValPrev: {
    width: 110,
  },
  priceText: {
    fontSize: 14,
    color: '#ff8a00'
  },
  inputOper: {
    height: 24 + 1 / PixelRatio.get()*2,
    width: 28 + 1 / PixelRatio.get()*2,
    justifyContent: 'center',
    alignItems: 'center',
    borderTopWidth: 1 / PixelRatio.get(),
    borderTopColor: '#e1e1e1',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#e1e1e1',
  },
  minus: {
    borderLeftWidth: 1 / PixelRatio.get(),
    borderLeftColor: '#e1e1e1',
  },
  plus: {
    borderRightWidth: 1 / PixelRatio.get(),
    borderRightColor: '#e1e1e1',
  },
  inputIcon: {
    width: 12,
    height: 12,
  }
});


module.exports = SpecList;
